package Comment

import (
	"FromNowOnPromote/博客系统/Tblog/controllers"
	"FromNowOnPromote/博客系统/Tblog/models"
	"FromNowOnPromote/博客系统/Tblog/models/Comment"
	"FromNowOnPromote/博客系统/Tblog/models/User"
	"FromNowOnPromote/博客系统/Tblog/redis"
	"encoding/json"
	"strconv"
)

type RecvComment struct {
	controllers.MainController
}

//接收的数据
type CommentRequest struct {
	BlogId  int    `json:"BlogId"`  //博客Id
	Comment string `json:"Comment"` //评论内容
	ToId    int    `json:"ToId"`    //评论目标Id
}

func (this *RecvComment) Post() {
	rd := redis.R.Conn
	defer rd.Close()
	//获取用户id
	uuid := this.Ctx.GetCookie("uuid")
	userid, err1 := rd.Get(uuid)
	if err1 != nil || userid == "" {
		body := map[string]interface{}{"code": 300}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//解析请求体
	var cr CommentRequest
	r := this.Ctx.Request
	decoder := json.NewDecoder(r.Body)
	err2 := decoder.Decode(&cr)
	if err2 != nil {
		body := map[string]interface{}{"code": 301}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	//评论数据插库
	db := models.ConnDb()
	defer db.Close()
	fromId, _ := strconv.Atoi(userid)
	comment := Comment.UserComment{BId: cr.BlogId, Content: cr.Comment, FromId: fromId, ToId: cr.ToId}
	err3 := db.Create(&comment).Error
	if err3 != nil {
		body := map[string]interface{}{"code": 302}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	body := map[string]interface{}{"code": 200, "data": "操作成功"}
	this.Data["json"] = body
	this.ServeJSON()
}

type SendComment struct {
	controllers.MainController
}

type Request struct {
	BlogId int `json:"blogId"`
}

type Response struct {
	BId     int
	Content string
	FromId  int
	ToId    int

	Username string
	IconUrl  string
	Toname   string
}

func (this *SendComment) Post() {
	var req Request
	r := this.Ctx.Request
	decoder := json.NewDecoder(r.Body)
	err1 := decoder.Decode(&req)
	if err1 != nil {
		body := map[string]interface{}{"code": 300}
		this.Data["json"] = body
		this.ServeJSON()
		return
	}
	db := models.ConnDb()
	defer db.Close()
	var resps []Response
	//from_id去重
	db.Raw("select * from tbuser,usercomment where usercomment.from_id = tbuser.uuid  and usercomment.b_id=?", req.BlogId).Scan(&resps)
	var tn User.TbUser
	for i := 0; i < len(resps); i++ {
		if resps[i].ToId != 0 {
			db.Raw("select username from tbuser where uuid = ?", resps[i].ToId).Scan(&tn)
			resps[i].Toname = tn.Username
		}
	}

	body := map[string]interface{}{"code": 200, "data": resps}
	this.Data["json"] = body
	this.ServeJSON()
}
